<?php
/*
 * 体现
 */
namespace Mobile\Controller;
use Mobile\Model\withdrawModel;
use Mobile\Model\tmpmsgModel;
use Mobile\Model\bankcomModel;//银行列表

class WithdrawController extends BaseController {
    
    public $withdrawModel;
    public $bankcomModel;
    public $banks;
    public $smscodeModel;


    public function __construct() {
        parent::__construct();
        $this->withdrawModel = new withdrawModel();
        $this->smscodeModel = new \Mobile\Model\smscodeModel();
    }
    
    /*
     * 兑换
     */
    public function index(){
        $seo_data = array(
            "title" => C('YONGJIN_NAME')."兑换",
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        $w = date('w');
        if($w!=4 && $w!=5) {
            $this->error2('仅限周四周五提现');
        }
        $share_data = array(
            "title" => C('YONGJIN_NAME')."兑换",
        );
        $this->setShare($share_data);
        
        //获取我的最近一条兑换记录
        $where = array(
            "uid" => $this->uid
        );
        $res = $this->withdrawModel->getWithdraw($where);
        $this->assign('mycard',$res);
        
        $withdraw_double = C('WITHDRAW_DOUBLE');
        $withdraw_rate = C('WITHDRAW_RATE');
        $this->assign('withdraw_double',$withdraw_double);
        $this->assign('withdraw_rate',$withdraw_rate);
        
        $max_times = floor($this->memberinfo['money']/$withdraw_double);
        $this->assign('max_times',$max_times);
        
        $this->bankcomModel = new bankcomModel();
        $banklist = $this->bankcomModel->getBankcomLists(array('status'=>1));
        $this->assign('banks',$banklist);
        
        $max_shouxufei = C('MAX_SHOUXU');//手续费封顶
        
        $this->assign('max_shouxufei',$max_shouxufei);//手续费封顶
        
        $this->display();
    }
    
    
    /*
     * 兑换ajax
     */
    public function tixian(){
        
        if(!IS_AJAX){
            return_json(1,"提交方式错误");
        }
        $w = date('w');
        if($w!=4 && $w!=5) {
            return_json(1,"仅限周四周五提现");
        }
        $must = array(
            "realname","bankname","mobile","atm_money"
        );
        $allow =array(
            "realname","bankname","mobile","alipay","atm_money","kaihuhang","bankcard","smscode",'code_id'
        );
        
        
        if($_POST['bankname'] != "微信钱包"){
            if(empty($_POST['kaihuhang']) OR empty($_POST['bankcard'])){
                return_json(1,"请检查是否填写完整");
            }
        }else{
            $_POST['kaihuhang'] = "";
            $_POST['bankcard'] = "";
        }
        
        
        $data = param_filter($_POST, $allow,$must,true,true);
        if(empty($data)){
            return_json(1,"请检查是否填写完整");
        }
        
        
        //判断是否有足够的钱
        $memberinfo = $this->getMemberInfobyUid($this->uid);
        if($memberinfo['money'] < $data['atm_money']){
            return_json(1,"余额不足,兑换不了哦~");
        }
        
        
        $this->_checkCode($data);
        
        //判断是不是100的整数倍
        $withdraw_double = C('WITHDRAW_DOUBLE');
        $withdraw_rate = C('WITHDRAW_RATE');

        if($withdraw_double>0){
            if($data['atm_money']%$withdraw_double>0 || ($data['atm_money']<=0)){
                return_json(1,"兑换金额只能是".$withdraw_double."的整数倍哦");
            }
        }
        

        $data['shouxufei'] = $data['atm_money'] * $withdraw_rate;//兑换手续费
        $max_shouxufei = C('MAX_SHOUXU');//手续费封顶
        if($max_shouxufei>0){
            if($data['shouxufei']>$max_shouxufei){
                $data['shouxufei'] = $max_shouxufei;//手续费封顶
            }
        }
        
        $tixian_money = round($data['atm_money']-$data['shouxufei'],2);
        
        //扣除佣金
        $data_money = array(
            "money" => array("exp","money-".$data['atm_money']),
            "tixian" => array("exp","tixian+".$data['atm_money']),
            "geshui_money" => array("exp","geshui_money+".$data['shouxufei']),
        );
        $res = $this->updateMemberInfoByUid($this->uid, $data_money);
        
        $data['openid'] = $this->memberinfo['openid'];
        
        if($res){
            //写兑换记录,流水
            $data['uid'] = $this->uid;
            $data['create_time'] = date("Y-m-d H:i:s");
            $data['update_time'] = date("Y-m-d H:i:s");
            $data["status"] = 0;
            $data['withdraw_money'] = $tixian_money;
            
            
            $withdraw = $this->withdrawModel->addWithdraw($data);
            if($withdraw){
                //发送模板消息
                $this->_tixianMsg($data);//给用户发兑换通知
                $uids = C('NEW_WITHDRAW_UIDS');
                $managers = $this->memberModel->where(array('uid'=>array('in',$uids)))->select();
                foreach ($managers as $manager) {
                    $this->_newWithdraw($manager, $data);
                }
                return_json(0,"已提交申请,请等待财务审核","","/mobile/withdraw/lists");
            }
        }
        
        return_json(1,"申请失败");
        
    }
    
    

    /*
     * 兑换提醒
     */
    protected function _tixianMsg($tixian){
        //判断是否关注, 没关注就别发了

        $userinfo = $this->memberinfo;
    
        if(!$userinfo['openid']){
            //TODO
            return false;
        }
        //发送模板消息
        $msg = $this->_tixianTmp($tixian,$userinfo);//拼接模板消息
    
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }
    
    
    
    
    
    /*
     * 升级消息
     *
     {{first.DATA}}
    
     兑换金额:{{money.DATA}}
     兑换时间:{{timet.DATA}}
     {{remark.DATA}}
    
     * 拼接模板消息
     */
    protected function _tixianTmp($tixian,$userinfo){
    
        $tmp_id = $this->tmpl['TIXIAN_TIJIAO']['tmp_id'];
		$color = $this->tmpl['TIXIAN_TIJIAO']['color'];
    
        $url = get_domain()."/mobile/withdraw/lists/";
        $footer ='\\n'."点击查看详情...";
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode("你提交了兑换申请,请等待管理员审核~"),
                    'color' => $color
                ),
                'money' => array(
                    'value' => urlencode($tixian['atm_money']."元"),//原先等级
                    'color' => $color,
                ),
                'timet' => array(
                    'value' => urlencode($tixian['create_time']),//new等级
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }   
    
    /*
     * 兑换列表
     */
    public function lists(){
        
        $seo_data = array(
            "title" => $this->lang['withdraw_list'],
            "description" => "",
            "keywords" => "",
        );
        //0提交待审核,1财务已打款,2审核拒绝
        $status = array(
            0 => "<em style='color:orange;'>待审核</em>",
            1 => "<em style='color:green;'>已通过</em>",
            2 => "<em style='color:red;'>审核拒绝</em>"
        );
        $status = json_encode($status,true);
        
        $this->setSeo($seo_data);
        
        

        $page_size = C("MOBILE_PAGESIZE");//分页条数
        $page = get("p",1);
        $where = array(
            "uid" => $this->uid
        );
        
        $datalist = $this->withdrawModel->getWithdrawList($where,$page,$page_size);
        
        $a_count = $this->withdrawModel->where($where)->count();//总的记录数量
        $totalpage = ceil($a_count/$page_size);//向上取整,总的页码数
        $this->assign('totalpage',$totalpage);
        
        
        
        
        
        if(IS_AJAX){
            exit_json($datalist);
          
        }
        
        
        
       
        $this->assign('status',$status);
        $this->assign('datalist',$datalist);
        
        $share_data = array(
            "title" => $this->lang['withdraw_list'],
        );
        $this->setShare($share_data);
        
        $this->display();
    }
    
    
    /*
     * 发送手机验证码
     */
    public function sendsms(){
       
        $mobile = get('mobile');
        if(!check_mobile($mobile)){
            return_json(1,"请检查手机号是否正确");
        }
        
        if(!IS_AJAX){
            return_json(1,"提交方式有误");
        }
        
       
        
        //判断是否超出频率限制
        //短信验证码，使用同一个签名，对同一个手机号码发送短信验证码，允许每分钟1条，累计每小时7条。
        $time1 = date("Y-m-d H:i:s");//当前时间
        $time2 = date("Y-m-d H:i:s",time()-60);//60秒前
        $time3 = date("Y-m-d H:i:s",time()-60*60);//1小时前
        $today1 = date("Y-m-d H:i:s",strtotime(date("Y-m-d")));//今天的时间
        

        $where_min = array(
            "mobile" => $mobile,
            "send_status" => 1,
            "create_time" => array(
                "between" => array(
                    $time1,$time2
                )
            )
        );
        $count_min = $this->smscodeModel->getSmscodeCount($where_min);
        if($count_min>=1){
            return_json(1,"请稍等60秒后重新获取");
        }
        
        $where_hour = array(
            "mobile" => $mobile,
            "send_status" => 1,
            "create_time" => array(
                "between" => array(
                    $time1,$time3
                )
            )
        );
        $count_hour = $this->smscodeModel->getSmscodeCount($where_hour);
        if($count_hour>=7){
            return_json(1,"请稍等1个小时后重新获取");
        }
       
        
        //发送短信
        $code = rand(1000,9999);
        $data = array(
            "code" => "$code",
            "product" => C('SMS_SIGN')
        );
        
        //将信息存储到数据库
        $save_data = array(
            "uid" => $this->uid,
            "smssign" => C('ALIDAYU_SIGN'),
            "mobile" => $mobile,
            "tmpid" => C('ALIDAYU_SHENFEN_TMP'),
            "content" => json_encode($data),
            "code" => $code,
            "create_time" => date("Y-m-d H:i:s"),
            "expired_time" => date("Y-m-d H:i:s",time()+5*60),
            "ip" => get_client_ip(),
            "try_time" => 0,
            "status" => 1,
        );
        
        $res = alisms(C('ALIDAYU_SIGN'),$mobile,C('ALIDAYU_SHENFEN_TMP'),$data);
        if($res['result']['success']){
            //发送成功
            //存储数据
            $save_data['send_status'] = 1;
            $code_id = $this->smscodeModel->addSmscode($save_data);
            return_json(0,"",$code_id);
        }else{
            //发送失败
            //echo $resp['result']['err_code'];
            $msg = "发送失败,请稍后重试。错误原因:".$res['sub_msg'];
            $save_data['send_status'] = 0;
            $this->smscodeModel->addSmscode($save_data);
            return_json(1,$msg);
            //短信验证码，使用同一个签名，对同一个手机号码发送短信验证码，允许每分钟1条，累计每小时7条。
            //短信通知，使用同一签名、同一模板，对同一手机号发送短信通知，允许每天50条（自然日）。
        }
        
    }
    
    
    protected function _checkCode($data){
        if(!$data['smscode']) {
            return_json(1,'请输入验证码');
        }
        //检查验证码是否正确
        $codewhere = array(
            "code_id" => $data['code_id'],
            "code" => $data['smscode'],
            "mobile" => $data['mobile'],
        );
        $code_id = $data['code_id'];
        $res = $this->smscodeModel->where($codewhere)->find();
        if(!$res){
            //将尝试次数加1
            $this->smscodeModel->where(array("code_id"=>$code_id))->setInc('try_time');//将尝试次数加1
            return_json(1,"验证码错误");
        }
        
        //if($res['ip'] != $ip){
          //  $this->smscodeModel->where(array("code_id"=>$code_id))->setInc('try_time');//将尝试次数加1
          //  return_json(1,"你的网络有风险,已阻止此次验证!");
        //}
        
        if(strtotime($res['expired_time']) < time()){
            return_json(1,"验证码已过期,请重新获取!");
        }
        
        if($res['try_time'] > 2){
            return_json(1,"验证码已失效,请重新获取!");
        }
        
        if($res['status'] != 1){
            return_json(1,"验证码已失效,请重新获取!");
        }
        
        //验证通过
        //将验证码作废
        $this->smscodeModel->where(array("code_id"=>$code_id))->setInc('try_time');//将尝试次数加1
        $this->smscodeModel->where(array("code_id"=>$code_id))->setField('status',0);
        return true;
        
    }
    
    public function prize() {
        parent::wxLogin();
        $seo_data = array(
            "title" => "奖励佣金兑换",
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        
        $share_data = array(
            "title" => "奖励佣金兑换",
        );
        $this->setShare($share_data);
        
        //获取我的最近一条兑换记录
        $where = array(
            "uid" => $this->uid
        );
        $res = $this->withdrawModel->getWithdraw($where);
        $this->assign('mycard',$res);
        
        $withdraw_double = C('WITHDRAW_DOUBLE');
        $withdraw_rate = C('WITHDRAW_RATE');
        $this->assign('withdraw_double',$withdraw_double);
        $this->assign('withdraw_rate',$withdraw_rate);
        
        $max_times = floor($this->memberinfo['prize_money']/$withdraw_double);
        $this->assign('max_times',$max_times);
        
        $this->bankcomModel = new bankcomModel();
        $banklist = $this->bankcomModel->getBankcomLists(array('status'=>1));
        $this->assign('banks',$banklist);
        
        $max_shouxufei = C('MAX_SHOUXU');//手续费封顶
        
        $this->assign('max_shouxufei',$max_shouxufei);//手续费封顶
        
        $this->display();
    }
    
     /*
     * 兑换ajax
      * 提现不超过16000元的部分扣税20%，16000至37000元部分扣税30%，超过37000元部分扣税40%
     */
    public function prizetixian(){
        
        if(!IS_AJAX){
            return_json(1,"提交方式错误");
        }
        $must = array(
            "realname","bankname","mobile","atm_money"
        );
        $allow =array(
            "realname","bankname","mobile","alipay","atm_money","kaihuhang","bankcard","smscode",'code_id',
            "account_type"
        );
        
        
        if($_POST['bankname'] != "微信钱包"){
            if(empty($_POST['kaihuhang']) OR empty($_POST['bankcard'])){
                return_json(1,"请检查是否填写完整");
            }
        }else{
            $_POST['kaihuhang'] = "";
            $_POST['bankcard'] = "";
        }
        
        
        $data = param_filter($_POST, $allow,$must,true,true);
        if(empty($data)){
            return_json(1,"请检查是否填写完整");
        }
        if(!$data['account_type']){
            return_json(1,'请选择提现方式');
        }
        
        //判断是否有足够的钱
        $memberinfo = $this->getMemberInfobyUid($this->uid);
        if($memberinfo['prize_money'] < $data['atm_money']){
            return_json(1,"余额不足,兑换不了哦~");
        }
        
        
        $this->_checkCode($data);
        
        //判断是不是100的整数倍
        $withdraw_double = C('WITHDRAW_DOUBLE');
        $withdraw_rate = C('WITHDRAW_RATE');

        if($withdraw_double>0){
            if($data['atm_money']%$withdraw_double>0 || ($data['atm_money']<=0)){
                return_json(1,"兑换金额只能是".$withdraw_double."的整数倍哦");
            }
        }
        

//        $data['shouxufei'] = $data['atm_money'] * $withdraw_rate;//兌換手續費
//        $max_shouxufei = C('MAX_SHOUXU');//手續費封頂
//        if($max_shouxufei>0){
//            if($data['shouxufei']>$max_shouxufei){
//                $data['shouxufei'] = $max_shouxufei;//手續費封頂
//            }
//        }
        if($data['account_type']==1){
            $data['shouxufei'] = $this->_getShouxuFei($data['atm_money']);
        }elseif($data['account_type']==2){
            $data['shouxufei'] = 0;
        }
        
        
        $tixian_money = round($data['atm_money']-$data['shouxufei'],2);
        
        //扣除佣金
        $data_money = array(
            "prize_money" => array("exp","prize_money-".$data['atm_money']),
            "tixian" => array("exp","tixian+".$data['atm_money']),
            "geshui_money" => array("exp","geshui_money+".$data['shouxufei']),
        );
        $res = $this->updateMemberInfoByUid($this->uid, $data_money);
        
        $data['openid'] = $this->memberinfo['openid'];
        
        if($res){
            //写兑换记录,流水
            $data['uid'] = $this->uid;
            $data['create_time'] = date("Y-m-d H:i:s");
            $data['update_time'] = date("Y-m-d H:i:s");
            $data["status"] = 0;
            $data['withdraw_money'] = $tixian_money;
            $data['type'] = 2;
            $data['account_type'] = $data['account_type'];
            
            
            $withdraw = $this->withdrawModel->addWithdraw($data);
            if($withdraw){
                //发送模板消息
                $this->_tixianMsg($data);//给用户发兑换通知
                return_json(0,"已提交申请,请等待财务审核","","/mobile/withdraw/lists");
            }
        }
        
        return_json(1,"申请失败");
        
    }
    
    /*
     * 提现不超过16000元的部分扣税20%，16000至37000元部分扣税30%，超过37000元部分扣税40%
     */
    protected function _getShouxuFei($money){
        $shouxufei = 0;
        if($money<=16000){
            $shouxufei += $money*0.2;
        }else if($money<=37000){
            $shouxufei += 16000*0.2;
            $shouxufei += ($money-16000)*0.3;
        }else if($money>37000){
            $shouxufei += 16000*0.2;
            $shouxufei += (37000-16000)*0.3;
            $shouxufei += ($money-37000)*0.4;
        }
        return $shouxufei;
    }
    
    
    protected function _newWithdraw($userinfo,$data){
        $tmp_id = $this->tmpl['NEW_WITHDRAW']['tmp_id'];
        $content = '你好,有新的提现申请';
        $footer ="请尽快登录后台审核".'\\n\\n';
        $color = '#000';
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode($content.'\\n'),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($data['realname']),
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode(date('Y-m-d H:i:s')),
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode($data['atm_money']),
                    'color' => $color,
                ),
                'keyword4' => array(
                    'value' => urlencode($data['bankname']),
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => urldecode(json_encode($msg)),
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new \Mobile\Model\tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
        return true;
    }
    
    
    
    
    
    
    

    /*
     * 保证金
     */
    public function deposit(){
        $seo_data = array(
            "title" => "我的保证金",
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
    
        
        
        //获取我的最近一条兑换记录
        $where = array(
            "uid" => $this->uid
        );
        $res = $this->withdrawModel->getWithdraw($where);
        $this->assign('mycard',$res);
        
        $this->bankcomModel = new bankcomModel();
        $banklist = $this->bankcomModel->getBankcomLists(array('status'=>1));
        $this->assign('banks',$banklist);
        
        
        $this->display();
    }
    
    
    
    
    
    /*
     * 兑换ajax
     * 提现不超过16000元的部分扣税20%，16000至37000元部分扣税30%，超过37000元部分扣税40%
     */
    public function bzjtixian(){
    
        if(!IS_AJAX){
            return_json(1,"提交方式错误");
        }
        $must = array(
            "realname","bankname","mobile"
        );
        $allow =array(
            "realname","bankname","mobile","alipay","kaihuhang","bankcard","smscode",'code_id',
            "account_type"
        );
    
    
        if($_POST['bankname'] != "微信钱包"){
            if(empty($_POST['kaihuhang']) OR empty($_POST['bankcard'])){
                return_json(1,"请检查是否填写完整");
            }
        }else{
            $_POST['kaihuhang'] = "";
            $_POST['bankcard'] = "";
        }
    
    
        $data = param_filter($_POST, $allow,$must,true,true);
        if(empty($data)){
            return_json(1,"请检查是否填写完整");
        }

    
        //判断是否有足够的钱
        $memberinfo = $this->getMemberInfobyUid($this->uid);
        if($memberinfo['bzj_money'] <= 0){
            return_json(1,"余额不足,兑换不了哦~");
        }
    
    
        $this->_checkCode($data);
        
        $data['shouxufei'] = 0;//手續費封頂
        $data['atm_money'] = $memberinfo['bzj_money'];//手續費封頂
        
        //扣除佣金
        $data_money = array(
            "bzj_money" => 0,
        );
        $res = $this->updateMemberInfoByUid($this->uid, $data_money);
    
        $data['openid'] = $this->memberinfo['openid'];
    
        if($res){
            //写兑换记录,流水
            $data['uid'] = $this->uid;
            $data['create_time'] = date("Y-m-d H:i:s");
            $data['update_time'] = date("Y-m-d H:i:s");
            $data["status"] = 0;
            $data['withdraw_money'] = $memberinfo['bzj_money'];
            $data['type'] = 2;
            $data['account_type'] = 1;
            
            $data['note'] = "保证金提现";
            $data['message'] = "保证金提现";

            $withdraw = $this->withdrawModel->addWithdraw($data);
            if($withdraw){
                //发送模板消息
                $this->_tixianMsg($data);//给用户发兑换通知
                session_destroy();
                return_json(0,"已提交申请,请等待财务审核","","/mobile/withdraw/lists");
            }
        }
    
        return_json(1,"申请失败");
    
    }
    
    
    /*
     * 计算销量
     */
    protected function _jisuanxiaoliang($uid){
    
        //计算我自身的购买量
        $my_goumai = $this->memberModel->field("uid,refer_uid,jinhuo_nums")->where(array("uid"=>$uid))->find();
        if(!$my_goumai){
            return false;
        }
        //$jinhuo = $my_goumai['jinhuo_nums'];
    
        $jinhuo = 0;//不包括自己的进货量
         
        //计算销量
        $where_xiaji = array(
            "refer_uid" => $uid
        );
        $xiaji = $this->memberModel->where($where_xiaji)->field("uid,refer_uid")->select();
    
    
        while(!empty($xiaji)){
            //我有下级
            $jinhuo += $this->memberModel->where($where_xiaji)->sum("jinhuo_nums");
             
            $arr_uid = array();
            foreach ($xiaji as $k=>$v){
                $arr_uid[] = $v['uid'];
            }
            //计算县级代理
            $where_xiaji = array(
                'refer_uid' => array(
                    "IN",$arr_uid
                ),
            );
             
            $xiaji = $this->memberModel->where($where_xiaji)->field("uid,refer_uid")->select();
    
        }
    
        return $jinhuo ? $jinhuo : 0;
    }
    
    
    
    
    /*
     * 团队购买量纸盒
     */
    public function teambuy(){
        $seo_data = array(
            "title" => "团队总业绩",
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        
        
        $nums = $this->_jisuanxiaoliang($this->uid);
        
        $this->assign("sale_nums",$nums);
        
        $this->display();
    }
    
    
}